package com.iot.system.mqtt;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.iot.common.utils.RedisUtil;
import com.iot.common.utils.StringUtils;
import com.iot.system.domain.DeviceData;
import com.iot.system.service.IDeviceDataService;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author mayanbin
 * @date 2024/8/21
 * @description TODO
 **/

@Component
public class PushCallback implements MqttCallback {

    private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class);

    @Autowired
    private MqttConfig mqttConfig;
    @Autowired
    private IDeviceDataService iDeviceDataService;

    private static MqttClient client;

    private static String _topic;
    private static String _qos;
    private static String _msg;

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接断开，可以做重连");
        if (client == null || !client.isConnected()) {
            //mqttConfig.getMqttPushClient();
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        logger.info("接收消息主题 : " + topic);
        logger.info("接收消息Qos : " + mqttMessage.getQos());
        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));


        _topic = topic;
        _qos = mqttMessage.getQos()+"";
        _msg = new String(mqttMessage.getPayload());
        saveDeviceData(mqttMessage);
    }

    private void saveDeviceData(MqttMessage mqttMessage){
        String str = mqttMessage.toString();
        if (StringUtils.equals("{}",str)){
            return;
        }

        //获取上次上报结果
        String redis = RedisUtil.StringOps.get("mqtt:leyte:embroider");
        if (StringUtils.isEmpty(redis)){
            //判断redis是否存在 不存在则直接保存
            RedisUtil.StringOps.set("mqtt:leyte:embroider",str);
            return;
        }

        Map redisMapTypes = JSON.parseObject(redis);

        //获取当次上报结果
        Map mapTypes = JSON.parseObject(mqttMessage.toString());

        //时间转换切换时分秒
        String second = mapTypes.get("秒（记录运行时间）").toString();
        String minute = mapTypes.get("分（记录运行时间）").toString();
        String hour = mapTypes.get("时（记录运行时间）").toString();
        if(Integer.valueOf(minute)<10){
            minute='0'+minute;
        }
        if(Integer.valueOf(hour)<10){
            hour='0'+hour;
        }
        //时分秒 切换成生产计时
        String productionDate= hour+"-"+minute+"-"+second;

        mapTypes.forEach((key,val)->{
            //判断当前属性是否需要处理 目前处于调试阶段 按照定制类型处理
            //判断  故障0：解除 1：发生
            //判断  启动0：不启动 1：启动
            //判断  停止0：不停止 1：停止
            if (StringUtils.equals(key.toString(),"故障")){
                //判断当前故障状态和上次上报故障状态是否一致
                String malfunction = redisMapTypes.get("故障").toString();
                if (!StringUtils.equals(val.toString(),malfunction)){
                    saveDeviceData(key, val, productionDate);
                }
            }
            if (StringUtils.equals(key.toString(),"启动")){
                //判断当前启动状态和上次上报故障状态是否一致
                String start = redisMapTypes.get("启动").toString();
                if (!StringUtils.equals(val.toString(),start)){
                    saveDeviceData(key, val, productionDate);
                }
            }
            if (StringUtils.equals(key.toString(),"停止")){
                //判断当前停止状态和上次上报故障状态是否一致
                String end = redisMapTypes.get("停止").toString();
                if (!StringUtils.equals(val.toString(),end)){
                    saveDeviceData(key,val,productionDate);
                }
            }
            if (StringUtils.equals(key.toString(),"产量")){
                //判断当前停止状态和上次上报故障状态是否一致
                Integer outPut= (Integer)val - (Integer) redisMapTypes.get("产量");
                if (outPut>0){
                    saveDeviceData(key,outPut.toString(),productionDate);
                }
            }
        });
        RedisUtil.StringOps.set("mqtt:leyte:embroider",str);
    }

    /**
     * @Author myb
     * @Description 保存设备数据
     * @Date 上午9:09 2024/8/22
     * @Param [key, val, productionDate]  设备数据类型 设备数据 生产计时
     * @return void
     **/
    private void saveDeviceData(Object key, Object val, String productionDate) {
       /* DeviceData deviceData = new DeviceData();
        deviceData.setDeviceId(1);
        deviceData.setDeviceData(val.toString());
        deviceData.setDeviceType(key.toString());
        deviceData.setCreateName("测试人员");
        deviceData.setCreateTime(new Date());
        deviceData.setUpdateName("测试人员");
        deviceData.setUpdateTime(new Date());
        deviceData.setIsDeleted(0);
        deviceData.setTimer(productionDate);
        iDeviceDataService.insertDeviceData(deviceData);*/
    }


    /**
     * 参数回调的方法
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }

    //别的Controller层会调用这个方法来  获取  接收到的硬件数据
    public String receive() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("topic", _topic);
        jsonObject.put("qos", _qos);
        jsonObject.put("msg", _msg);
        return jsonObject.toString();
    }

}
